<template>
  <div
    class="page-container container"
    style="height: auto"
    v-loading="loading"
  >
    <!--@copy="copy" -->
    <!-- <docDetailInformaton></docDetailInformaton> -->
    <docDetailTab
      dataID=""
      class="tab"
      @save="save"
      @file="openUploadfile"
      @log="openLog"
      @refresh="refresh"
    >
    </docDetailTab>
    <div class="in-container content">
      <el-form
        ref="form"
        size="small"
        label-suffix="："
        :label-width="'100px'"
        :inline="true"
        :model="detailData"
        class="form"
      >
        <el-tabs v-model="activeName">
          <el-tab-pane label="基本信息" name="基本信息">
            <docDetailBase
              v-model:detailData="detailData"
              :initOption="allOption"
              :checkDisabled="checkDisabled"
            >
            </docDetailBase>
          </el-tab-pane>
          <el-tab-pane label="装箱信息" v-if="!isNew" name="装箱信息">
            <docDetailBox
              v-model:detailData="detailData"
              :initOption="allOption"
              ref="box"
            >
            </docDetailBox>
          </el-tab-pane>
          <el-tab-pane label="费用信息" v-if="!isNew" name="费用信息">
            <docDetailFee v-model:detailData="detailData"> </docDetailFee>
          </el-tab-pane>
          <el-tab-pane label="货代提单" v-if="!isNew" name="货代信息">
            <docDetailhbl
              v-model:detailData="hBillTableData"
              :alldata="detailData"
              :initOption="allOption"
              @changeVersion="handleChangeVersion($event)"
            >
            </docDetailhbl>
          </el-tab-pane>
          <el-tab-pane
            label="特货信息"
            v-if="
              detailData.cargoType &&
              detailData.cargoType != '普货' &&
              detailData.cargoType != 0
            "
          >
            <docDetailSpecialBox
              v-model:detailData="detailData"
              ref="specialBoxRef"
            >
            </docDetailSpecialBox>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
    <docDetailFileDialog
      v-model:show="fileShow"
      v-model:detailData="detailData"
      ref="docDetailFileDialogRef"
    >
    </docDetailFileDialog>
    <docDetailLogDialog v-model:show="logShow"> </docDetailLogDialog>
  </div>
</template>

<script>
import { defineComponent, computed } from 'vue'
import docDetailInformaton from './components/docDetailInformaton.vue'
import docDetailTab from './components/docDetailTab.vue'
import docDetailBase from './components/docDetailBase.vue'
import docDetailBaseCopy from './newBusiness/docDetailBaseCopy.vue'
import docDetailBox from './components/docDetailBox.vue'
import docDetailBoxCopy from './newBusiness/docDetailBoxCopy.vue'
import docDetailFee from './components/docDetailFee.vue'
import docDetailhbl from './components/docDetailhbl.vue'
import docDetailSpecialBox from './components/docDetailSpecialBox.vue'
import docDetailLogDialog from './components/docDetailLogDialog.vue'
import docDetailFileDialog from './components/docDetailFileDialog.vue'
import AppPageTable, { useTableOption } from '@/components/AppPageTable2'
import optionsStore from './components/getAllSelectOption'
import { ElLoading, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
export default defineComponent({
  components: {
    docDetailInformaton,
    docDetailTab,
    docDetailBase,
    docDetailBaseCopy,
    docDetailFee,
    docDetailBox,
    docDetailBoxCopy,
    docDetailhbl,
    docDetailSpecialBox,
    docDetailLogDialog,
    docDetailFileDialog
  },
  provide() {
    return {
      hBillBoxCopy: computed(() => {
        return this.hBillBoxCopy
      }),
      dataCopyFeeOut: () => this.dataCopyFeeOut,
      dataCopyFeeIn: () => this.dataCopyFeeIn
    }
  },
  data() {
    return {
      activeName: '基本信息',
      routeData: {
        id: '',
        title: '',
        iscopy: false
      },
      //所有数据
      detailData: {
        id: undefined,
        doccode: undefined, //单号
        blCount: undefined, //提单份数
        checkStatus: undefined, // 审核状态 0草稿 1提交审核 2已审 -1驳回.
        ctn20: undefined, //20gp
        ctn40: undefined, //40gp
        ctn40h: undefined, //20gp
        ctn45: undefined, //20gp，40GP，40HQ，45HQ
        ctn20Type: '20GP', //20gp
        ctn40Type: '40GP', //40gp
        ctn40HType: '40HQ', //20gp
        ctn45Type: '45HQ', //20gp
        // ctn20TypeWeight: 0,
        // ctn40TypeWeight: 0,
        // ctn40HTypeWeight: 0,
        // ctn45TypeWeight: 0,
        isLcl: undefined, //是否拼箱 0否  1是.
        isShutout: undefined, //退关 0否 1 是.
        isThrowOut: undefined, //甩柜 0否 1是.
        blNo: undefined, //提单号
        blType: undefined, //提单状态
        bookingAgentId: undefined, //订舱单位ID
        bookingAgentName: undefined,
        bookingAgentLinkId: undefined, //订舱单位联系人ID
        bookingId: undefined, //订舱员ID
        bookingName: undefined, //订舱员Name
        bookingMemo: undefined, //配船要求
        businessStatus: undefined, //业务进度
        cargoDescription: undefined, //品名描述
        cargoSource: undefined, //货物来源
        consigneeMemo: undefined, //收货人详细信息
        createBy: undefined, //录入人
        ctnMemo: undefined, //箱量描述
        custDocNo: undefined, //客户单号
        // custId: undefined, //客户ID
        custName: undefined, //客户名称
        customMemo: undefined, //报关备注
        customNo: undefined, //报关单号
        customsBrokerId: undefined, //报关行ID
        customsBrokerName: undefined, //报关行ID
        digit: undefined, //件数
        grossWeight: undefined, //毛重
        volume: undefined, // 体积
        hblBlno: undefined, //货代提单-提单号
        hblConsigneeMemo: undefined, //货代提单-收货人详细信息
        hblNotifyMemo: undefined, //货代提单-通知人详细信息.
        hblPayment: undefined, //货代提单-付款方式 引用数据字典.
        hblShipperMemo: undefined, //货代提单-发货人详细信息.
        marks: undefined, //唛头
        notifyMemo: undefined, //通知人详细信息.
        operaterId: undefined, //操作员ID
        operaterName: undefined, //操作员Name
        overseaAgentMemo: undefined, //海外代理详细信息
        packageUom: undefined, //包装单位
        payment: undefined, // 付款方式
        portDepartureId: undefined, // 装货港ID
        portDepartureName: undefined, // 装货港名称
        portDepartureEnName: undefined, // 装货港英文名称
        portDestinationId: undefined, // 目的港ID
        portDestinationName: undefined, // 目的港名称
        portDestinationEnName: undefined, // 目的港英文名称
        portDischargeId: undefined, // 卸货港ID
        portDischargeName: undefined, // 卸货港名称
        portDischargeEnName: undefined, // 卸货港英文名称
        portTransportId: undefined, // 中转港ID
        portTransportName: undefined, // 中转港名称
        portTransportEnName: undefined, // 中转港英文名称
        salesId: undefined, // 业务员ID
        salesName: undefined, // 业务员Name
        sendAddress: undefined, // 寄单地址
        shipcompanyId: undefined, // 航司ID
        shipcompanyName: undefined, // 航司ID
        shipperMemo: undefined, // 发货人详细信息
        threeDocNo: undefined, // 三联单号
        transport: undefined, // 运输方式
        transterm: undefined, // 运输条款
        updateBy: undefined, // 修改人
        vessel: undefined, // 船名
        vesselid: undefined,

        voyage: undefined, // 航次
        voyageId: undefined, // 航次ID
        warehousingId: undefined, // 仓库ID
        warehousingName: undefined, // 仓库ID
        warehousingMemo: undefined, // 仓库备注
        warehousingNo: undefined, // 进仓编号
        atd: undefined, // 实际开航日期
        bookingDate: undefined, // 订舱日期
        closingDate: undefined, // 截关日期
        createTime: undefined, // 录入时间
        customDate: undefined, // 申报日期
        etd: undefined, // 预计开航日期
        recDate: undefined, // 接单日期
        updateTime: undefined, // 修改时间
        tradelaneId: undefined, //航线
        tradelaneName: undefined, //航线
        blType: undefined, //提单类型
        listColor: '#606266', //列表颜色
        ieFlag: 0, //进出口类型
        ctnType: undefined, // 箱型
        ctnMemo: undefined, //箱型描述
        ctnNoDesc: undefined, //箱号描述
        custId: undefined, // 委托单位
        docWorkCtnList: [], //集装箱列表
        docWorkFeeList: [], //费用列表
        attachmentList: [], // 附件
        docWorkFeeOutList: [], //应付
        docWorkFeeInList: [], //应收
        docWorkHblList: [], //货代
        costLock: 0, //应付锁定
        incomeLock: 0, //应收锁定
        financeLock: 0, //财务锁定
        cargoType: '普货', //货物种类
        serviceId: undefined, //客服
        settleType: undefined, //结算方式
        isSoc: undefined, //isSoc
        secondNotifyMemo: undefined, // 第二通知人
        docCargoColdList: [], // 冷藏品
        docCargoDangerList: [], // 危险品
        docCargoOverList: [], // 超高品
        version: 0
      },
      //初始化数据副本 刷新判断使用
      detailDataCopy: {},
      // 费用信息的表格数据副本
      dataCopyFeeOut: [],
      dataCopyFeeIn: [],
      //初始options
      allOption: {},
      //是否新增页面
      isNew: true,
      //页面加载
      loading: false,
      newUser: this.$store.state.auth.user,
      //附件
      fileShow: false,
      //日志
      logShow: false,
      //货代提单
      hBillTableData: {
        data: [],
        options: useTableOption()
      },
      //货代提单装箱信息复制
      hBillBoxCopy: [],
      routeQuery: {
        id: '',
        title: '',
        iscopy: false
      },
      //件数、毛重、体积 在装箱信息-箱数合计有数据下 上锁
      checkDisabled: false
    }
  },
  methods: {
    /**
     * 初始化 要先获取值后初始化
     */
    initData() {
      this.loading = true
      this.$http
        .get(`/api/docWork/get`, {
          id: this.routeQuery.id
        })
        .then((res) => {
          if (res.status) {
            this.detailData = JSON.parse(JSON.stringify(res.data))
            this.dataCopyFeeOut = JSON.parse(
              JSON.stringify(res.data.docWorkFeeOutList)
            )
            this.dataCopyFeeIn = JSON.parse(
              JSON.stringify(res.data.docWorkFeeInList)
            )
            this.hBillBoxCopy = JSON.parse(
              JSON.stringify(res.data.docWorkCtnList)
            )
            if (this.detailData.docCargoDangerList.length > 0) {
              this.detailData.docCargoDangerList.forEach((item) => {
                item.ruleShow = false
              })
            }
            if (this.routeQuery.iscopy) {
              this.detailData.doccode = this.detailData.doccode + '复制'
            }
            this.gethBill(this.routeQuery.id)
            if (this.routeQuery.iscopy) {
              this.detailData.id = 0
            }
            optionsStore.mutations
              .getAllOptions(res.data)
              .then((inRes) => {
                this.allOption = optionsStore.state
                if (res.data.portDepartureId) {
                  this.allOption.zhgOption = [
                    {
                      id: res.data.portDepartureId,
                      value: res.data.portDepartureId,
                      label: `${res.data.portDepartureName} | ${res.data.portDepartureEnName}`
                    }
                  ]
                } else {
                  this.allOption.zhgOption = []
                }
                if (res.data.portDischargeId) {
                  this.allOption.xhgOption = [
                    {
                      id: res.data.portDischargeId,
                      value: res.data.portDischargeId,
                      label: `${res.data.portDischargeName} | ${res.data.portDischargeEnName}`
                    }
                  ]
                } else {
                  this.allOption.xhgOption = []
                }
                if (res.data.portDestinationId) {
                  this.allOption.mdgOption = [
                    {
                      id: res.data.portDestinationId,
                      value: res.data.portDestinationId,
                      label: `${res.data.portDestinationName} | ${res.data.portDestinationEnName}`
                    }
                  ]
                } else {
                  this.allOption.mdgOption = []
                }
                if (res.data.portTransportId) {
                  this.allOption.zzgOption = [
                    {
                      id: res.data.portTransportId,
                      value: res.data.portTransportId,
                      label: `${res.data.portTransportName} | ${res.data.portTransportEnName}`
                    }
                  ]
                } else {
                  this.allOption.zzgOption = []
                }
                if (res.data.tradelaneId) {
                  this.allOption.hxOption = [
                    {
                      id: res.data.tradelaneId,
                      value: res.data.tradelaneId,
                      label: res.data.tradelaneName
                    }
                  ]
                } else {
                  this.allOption.hxOption = []
                }
              })
              .finally(() => (this.loading = false))
          }
        })
    },
    /**
     * 获取货代提单数据
     * @param {number} id - 业务id
     */
    gethBill(id) {
      this.$http
        .get('/api/docworkhbill/query', {
          DocId: id,
          PageIndex: 1,
          PageSize: 10
        })
        .then((res) => {
          this.hBillTableData.data = res.content
          this.hBillTableData.options.total = res.totalElements
        })
    },
    /**
     * 新增初始化
     */
    initNewData() {
      this.detailData.transterm = 'CY-CY'
      this.detailData.transport = '海运'
      this.detailData.payment = 'PP'
      this.detailData.businessStatus = '客户订舱'
      this.detailData.createBy = this.newUser.username
      this.detailData.createTime = dayjs(new Date()).format(
        'YYYY-MM-DD HH:mm:ss'
      )
      this.detailData.recDate = dayjs(new Date()).format('YYYY-MM-DD')
      this.detailData.checkStatus = 0
      this.loading = true
      optionsStore.mutations
        .getAllOptions(this.detailData)
        .then((inRes) => {
          this.allOption = optionsStore.state
          this.detailData.operaterId = this.newUser.id
          this.detailData.salesId = this.newUser.id
          this.detailData.bookingId = this.newUser.id
          this.allOption.ywyOption = [
            {
              id: this.newUser.id,
              value: this.newUser.id,
              label: this.newUser.username,
              selectLabel: this.newUser.username
            }
          ]
          this.allOption.czyOption = [
            {
              id: this.newUser.id,
              value: this.newUser.id,
              label: this.newUser.username,
              selectLabel: this.newUser.username
            }
          ]
          this.allOption.dcyOption = [
            {
              id: this.newUser.id,
              value: this.newUser.id,
              label: this.newUser.username,
              selectLabel: this.newUser.username
            }
          ]
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => (this.loading = false))
    },
    /**
     * 保存
     */
    async save() {
      this.perSaveBill()
      if (this.isNew) {
        this.toSaveBill()
      } else {
        if (!this.$refs.box.validChildData()) {
          return false
        }
        if (this.detailData.cargoType == '危险品') {
          const boxVaild =
            await this.$refs.specialBoxRef.$refs.dangerBoxRef.validData()

          if (!boxVaild) {
            return false
          }
        }
        if (!this.$refs.box.validBoxTotle()) {
          ElMessageBox.confirm(
            '装箱信息箱型箱量和箱数合计信息不一致，是否继续保存？',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              this.toSaveBill()
            })
            .catch(() => {
              return false
            })
        } else {
          this.toSaveBill()
        }
      }
    },
    perSaveBill() {
      if (!this.detailData.ctn20) {
        this.detailData.ctn20 = undefined
      }
      if (!this.detailData.ctn40) {
        this.detailData.ctn40 = undefined
      }
      if (!this.detailData.ctn40h) {
        this.detailData.ctn40h = undefined
      }
      if (!this.detailData.ctn45) {
        this.detailData.ctn45 = undefined
      }
    },
    toSaveBill() {
      if (this.isNew) {
        this.$http
          .post('/api/docwork/SaveBill', this.detailData)
          .then((res) => {
            if (res.status) {
              this.$message.success(res.message)
              this.$router.closeAndRefreshTab({
                path: '/business/docDetail',
                query: {
                  id: res.data.id,
                  title: `业务详情${res.data.doccode}`,
                  iscopy: false
                }
              })
            } else {
              this.$message.error(res.message)
            }
          })
      } else {
        if (this.detailData.docWorkFeeInList) {
          this.detailData.docWorkFeeInList.forEach((t) => {
            t.seqId = t.index + 1
          })
        }
        if (this.detailData.docWorkFeeOutList) {
          this.detailData.docWorkFeeOutList.forEach((t) => {
            t.seqId = t.index + 1
          })
        }
        if (this.routeQuery.iscopy) {
          this.$http
            .post('/api/docwork/SaveBill', this.detailData)
            .then((res) => {
              if (res.status) {
                this.$message.success(res.message)
                this.$router.closeAndRefreshTab({
                  path: '/business/docDetail',
                  query: {
                    id: res.data.id,
                    title: `业务详情${res.data.doccode}`,
                    iscopy: false
                  }
                })
              } else {
                this.$message.error(res.message)
              }
            })
        } else {
          this.$http
            .post('/api/docwork/SaveBill', this.detailData)
            .then((res) => {
              if (res.status) {
                this.$message.success(res.message)
                this.initData()
              } else {
                this.$message.error(res.message)
              }
            })
        }
      }
    },
    /**
     * 复制
     */
    copy() {
      if (this.isNew) {
        this.$message.warning('请先保存')
      } else if (this.routeQuery.iscopy) {
        this.$message.warning('已经是复制业务')
      } else {
        this.$router.openTab({
          path: '/business/docDetail',
          query: {
            id: this.routeQuery.id,
            title: `${this.routeQuery.title}复制`,
            iscopy: true
          }
        })
      }
    },
    /**
     * 附件
     */
    openUploadfile() {
      if (this.isNew) {
        this.$message.warning('请先保存')
      } else if (this.routeQuery.iscopy) {
        this.$message.warning('请先保存')
      } else {
        this.fileShow = true
        this.$refs.docDetailFileDialogRef.getFileTableData()
      }
    },
    /**
     * 日志
     */
    openLog() {
      if (this.isNew) {
        this.$message.warning('请先保存')
      } else if (this.routeQuery.iscopy) {
        this.$message.warning('请先保存')
      } else {
        this.logShow = true
      }
    },
    /**
     * 刷新
     */
    refresh() {
      if (this.isNew) {
        this.$message.warning('请先保存')
      } else if (this.routeQuery.iscopy) {
        this.$message.warning('请先保存')
      } else {
        // this.$http
        //   .get("/api/docWork/get", { id: this.routeQuery.id })
        //   .then((res) => {
        //     if (res.status) {
        //       this.detailData = res.data;
        //       this.$message.success(res.message);
        //     }
        //   });
        this.initData()
      }
    },
    handleChangeVersion(e) {
      this.detailData.version = e
    }
  },
  watch: {
    /**
     * 基本信息下的件数、毛重、体积 在装箱信息-箱数合计有数据下 上锁
     */
    'detailData.docWorkCtnList': {
      handler(newVal) {
        if (newVal.length == 0) {
          this.checkDisabled = false
        } else {
          let grossWeight = 0
          let digit = 0
          let volume = 0
          newVal.forEach((row) => {
            grossWeight = grossWeight + row.grossWeight
            digit = digit + Number(row.digit)
            volume = volume + row.volume
          })
          this.checkDisabled = grossWeight > 0 || digit > 0 || volume > 0
          if (this.checkDisabled) {
            this.detailData.digit = digit
            this.detailData.grossWeight = grossWeight
            this.detailData.volume = volume
          }
        }
      },
      deep: true
    }
  },
  mounted() {
    if (this.$route.query != {}) {
      this.$store.dispatch('tab/modifyTabTitle', {
        path: this.$route.fullPath,
        title: this.$route.query.title
      })
      this.isNew = this.$route.query.title == '新增业务'
      if (this.isNew) {
        this.initNewData()
      } else {
        this.routeQuery.id = this.$route.query.id
        this.routeQuery.title = this.$route.query.title
        this.routeQuery.iscopy =
          typeof this.$route.query.iscopy == 'string'
            ? this.$route.query.iscopy == 'true'
              ? true
              : false
            : this.$route.query.iscopy

        this.initData()
      }
      this.activeName = this.$route.query.tab
    }
  }
})
</script>

<style lang="scss" scoped>
.tab {
  margin-bottom: 8px;
}

.container {
  display: flex;
  flex-direction: column;

  .content {
    flex: 1;
    height: auto;
    padding: 0 0 8px 0;
  }

  :deep(.el-radio-group) {
    height: 28px;
  }

  :deep(.el-radio) {
    margin-right: 15px;

    .el-radio__inner {
      width: 12px;
      height: 12px;
    }

    .el-radio__label {
      font-size: 12px;
    }
  }

  :deep(.el-form-item) {
    width: 100%;
  }

  :deep(.el-select) {
    // width: 100%;
  }

  :deep(.el-date-editor) {
    width: 100%;
  }

  :deep(.el-tabs) {
    height: 100%;

    .el-tabs__header {
      padding: 0 16px;
    }

    .el-tabs__content {
      height: calc(100% - 55px);

      .el-tab-pane {
        height: 100%;
      }
    }
  }

  .form {
    height: 100%;
  }
}
</style>
